<template>
	<w-app-page class="scm8-pad__login">
		<w-header title="bar" :showBackBtn="false"></w-header>
		<div class="scm8-pad__login-content">
			<div class="scm8-pad__login-container">
				<div class="scm8-pad__login-form">
					<a-form>
						<a-form-item v-bind="validateInfos.username">
							<a-input
								v-model:value="modelRef.username"
								allowClear
								placeholder="用户名"
								class="form-input"
							/>
						</a-form-item>
						<a-form-item v-bind="validateInfos.password">
							<a-input-password v-model:value="modelRef.password" placeholder="密码" class="form-input" @pressEnter="onLoginClick"/>
						</a-form-item>
					</a-form>
					<a-button type="primary" shape="round" class="login-btn" @click="onLoginClick">登录</a-button>
				</div>
			</div>
		</div>
		<div class="login-bottom">
			<div class="version">version:{{appVersion}}</div>
		</div>
	</w-app-page>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store'
import { getFxInstance } from '@/js/instance'
import { Form } from 'ant-design-vue'
import { useDefaultDomain, isUseAppVersionUpdate, useGrayDefaultDomain } from '@/config/env.config'
import { login } from '@/js/api/bar'
import { setToken } from '@/utils/auth'

const useForm = Form.useForm
export default defineComponent({
	name: 'login-page',
	setup () {
		const fxInstance = getFxInstance()
		const route = useRoute()
		const router = useRouter()
		const store = useStore()
		const appVersion = computed(() => store.state.system.appVersion)
		const defaultDomainText = ref('.engine.fxscm.net')
		const isDefaultDomain = ref(useDefaultDomain())
		const isGrayDefaultDomain = ref(useGrayDefaultDomain())
		const domainText = computed(() => isDefaultDomain.value ? '供应链域名' : '供应链IP或域名')
		const loginSilentFlag = computed(() => store.state.loginer.loginSilentFlag)
		// {{{ form
		const getDefaultDomain = () => {
			const domain = store.state.loginer.domain
			if (isDefaultDomain.value) {
				return domain.split('.')[0]
			}
			return domain
		}
		const getCompleteDomain = () => {
			if (isDefaultDomain.value) {
				return `${modelRef.domain}${defaultDomainText.value}`
			}
			return modelRef.domain
		}
		const modelRef = reactive({
			domain: getDefaultDomain(),
			username: store.state.loginer.username,
			password: store.state.loginer.password
		})
		const rulesRef = reactive({
			username: [{
				required: true,
				message: '请填写用户名'
			}],
			password: [{
				required: true,
				message: '请填写密码'
			}]
		})
		const { validate, validateInfos } = useForm(modelRef, rulesRef)
		const onLoginClick = () => {
			validate()
				.then(loginHandler)
		}
		const loginHandler = () => {
			store.commit('SET_LOGINER', {
				token: ''
			})
			const params = {
				username: modelRef.username,
				password: modelRef.password
			}
			login(params).then((res) => {
				setToken(res.token)
				store.commit('SET_LOGINER', {
					username: params.username,
					password: params.password,
					token: res.token
				})
				store.dispatch('syncLoginer')
			}).then(() => {
				router.push('tableBar')
			})
			// return fxInstance.$fxApi('common.login')({ data: params }).then((res: { token: string }) => {
			// 	store.commit('SET_LOGINER', {
			// 		username: params.username,
			// 		password: params.password,
			// 		token: res.token
			// 	})
			// 	return Promise.resolve()
			// })
		}
		const onDomainBlur = () => {
			setHostIdAndBaseUrl()
		}
		// }}}
		// {{{ domainReadonly
		const domainReadonly = ref(false)
		const setDomainReadonly = () => {
			if (route.query.domainReadonly) {
				domainReadonly.value = route.query.domainReadonly === 'true'
			}
		}
		// }}}
		// {{{ domain
		const setDomain = () => {
			const domain = (route.query.domain as string)
			if (domain) {
				modelRef.domain = domain.includes('.') ? domain.split('.')[0] : domain
			}
		}
		const getInfoByDomain = ():{[key:string]:string} => {
			const domain = getCompleteDomain()
			let hostId = ''
			let baseUrl = ''
			if (domain.includes('?')) {
				const [_baseUrl, _query] = domain.split('?')
				baseUrl = _baseUrl
				const query = fxInstance.$fxUtils.parameters2json(_query)
				hostId = query.hostId
			} else {
				baseUrl = isGrayDefaultDomain.value ? 'scmpad-gray.engine.fxscm.net' : domain
				hostId = getHostByDomain(domain)
			}
			return {
				baseUrl,
				hostId
			}
		}
		const getHostByDomain = (domian:string) => {
			if (domian.includes('.')) {
				return domian.split('.')[0]
			}
			return ''
		}
		const setHostIdAndBaseUrl = () => {
			const { baseUrl, hostId } = getInfoByDomain()
			store.commit('SET_LOGINER', {
				baseUrl,
				hostId
			})
		}
		// }}}
		// {{{
		const verCheck = () => {
			if (isUseAppVersionUpdate()) {
				return fxInstance.$fxCordova.appVersion.checkAppVersion()
			}
			return Promise.resolve()
		}
		// }}}
		const setSystemIframe = () => {
			store.commit('SET_SYSTEM', {
				isIframe: route.query.iframe === 'true',
				isByRedirectPage: false
			})
		}
		const loginDefault = () => {
			if (modelRef.domain && modelRef.username && modelRef.password && loginSilentFlag.value) {
				onLoginClick()
			}
		}
		const pageInit = () => {
			setDomain()
			setDomainReadonly()
			setHostIdAndBaseUrl()
			setSystemIframe()
			verCheck().then(loginDefault)
		}
		pageInit()
		return {
			appVersion,
			defaultDomainText,
			isDefaultDomain,
			domainText,
			validateInfos,
			modelRef,
			onLoginClick,
			onDomainBlur,
			domainReadonly
		}
	}
})
</script>
<style lang="scss" scoped>
@import "$assets/stylus/varsty";
.scm8-pad__login {
	display: flex;
	align-items: center;
	background-position: center;
	background-repeat: no-repeat;
	background-size: 300%;
	background-image: url("$images/img/login/login_bg.png");
	&-content {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	&-container {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 520px;
		height: 360px;
		border-radius: 10px;
		background-color: #ffffff5e;
	}
	&-form {
		width: 466px;
		:deep(.form-input) {
			border-radius: 24px;
		}
		.form-input {
			padding-left: 20px;
			height: 46px;
			&.is-short {
				:deep(.ant-input) {
					margin-right: 150px;
					width: 300px;
				}
			}
		}
		.domain-text {
			position: absolute;
			top: 11px;
			right: 40px;
			z-index: 1;
		}
	}
	.login-btn {
		width: 100%;
		height: 46px;
	}
	.login-bottom {
		.version {
			color: $fxWhite
		}
	}
}
</style>
